//
//  HLURLManager.m
//  HealthyLifestyle
//
//  Created by 找汽配 on 2016/11/11.
//  Copyright © 2016年 HealthyLifestyle. All rights reserved.
//

#import "XYSearchHistoryManager.h"

@implementation XYSearchHistoryManager

DEF_SINGLETON(XYSearchHistoryManager)

+ (NSString *)key {
    return nil;
}

+ (NSArray<NSDictionary *>*)queryHistory {
    NSString * key = [self key];
    if (!key) {
        return nil;
    }
    
    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}

+ (void)addHistoryWithSearchType:(SearchType)type keyword:(NSString *)keyword {
    NSString * key = [self key];
    if (!key) {
        return;
    }
    
    if (keyword.length <= 0) {
        return;
    }
    
    NSMutableArray<NSDictionary *>* mArray = [[[NSUserDefaults standardUserDefaults] objectForKey:key] mutableCopy];
    if (!mArray) {
        mArray = [NSMutableArray array];
    }
    __block NSDictionary * dictionary = nil;
    [mArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj[@"keyword"] isEqualToString:keyword] && [obj[@"type"] isEqualToNumber:@(type)]) {
            dictionary = obj;
            *stop = YES;
        }
    }];
    if (dictionary) {
        [mArray removeObject:dictionary];
    }
    else {
        dictionary = @{@"keyword":keyword, @"type":@(type)};
    }
    [mArray insertObject:dictionary atIndex:0];
    [[NSUserDefaults standardUserDefaults] setObject:mArray forKey:key];
}

+ (void)clearHistory {
    NSString * key = [self key];
    if (!key) {
        return;
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:key];
}

@end
